<?php

	class Devmod_method_onEventBind extends Devmod_methods_abstraction {
		
		protected $after_finalized = array(array(
										'for_method' => 'save',
										'for_method_type' => 'frontend_add',
										'use' => 'bind_event'
									),array(
										'for_method' => 'save',
										'for_method_type' => 'add',
										'use' => 'bind_event'
									));
		
		public function set_config($args) {
			
			$opt_arg = null; 
			
			if(isset($args[1])) {
				$opt_arg = $args[1];
			}
			
			$this->update_config('event_bind', array(array(
				'function_def' => $args[0],
				'args' => $opt_arg
			)));
		
		}
		
		public function bind_event($return)
		{
			if($return === false) return $return;
			
			$arr = $this->config[$this->type]['event_bind'];
			
			foreach($arr as $event)
			{
				if(function_exists($event['function_def']))
				{
					// observe and replace field args
					if(!empty($event['args']) && isset($event['args']))
					{
						$event['args'] = $this->helper->eval_value($return, $event['args'], "%%result%%"); // replace %%result%%
						
						foreach($event['args'] as $key => $arg)
						{
							$event['args'][$key] = $this->helper->eval_vars($arg, $this->config[$this->type]['sql_fields']);
						}
					}
					
					$return = call_user_func_array($event['function_def'], $event['args']);
					
					// args are ready call user func now
				} else {
					$event['function_def'] = str_replace("%%result%%", $return, $event['function_def']); // replace %%result%%
					
					$event['function_def'] = $this->helper->eval_vars($event['function_def'], $this->config[$this->type]['sql_fields']);
					
					$new_function = create_function('$db', trim($event['function_def']));
					
					$return = $new_function(ydsql::getInstance());
				}
			}
			return $return;
		}
	}